// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/functions/prestosql/aggregates/bitwise_xor_aggregate.h>
#include <pollux/exec/simple_aggregate_adapter.h>
#include <pollux/functions/prestosql/aggregates/aggregate_names.h>

using namespace kumo::pollux::exec;

namespace kumo::pollux::aggregate::prestosql {
    namespace {
        template<typename T>
        class BitwiseXorAggregate {
        public:
            using InputType = Row<T>;

            using IntermediateType = T;

            using OutputType = T;

            static bool toIntermediate(exec::out_type<T> &out, exec::arg_type<T> in) {
                out = in;
                return true;
            }

            struct AccumulatorType {
                T xor_{0};

                AccumulatorType() = delete;

                explicit AccumulatorType(
                    HashStringAllocator * /*allocator*/,
                    BitwiseXorAggregate<T> * /*fn*/) {
                }

                void addInput(HashStringAllocator * /*allocator*/, exec::arg_type<T> data) {
                    xor_ ^= data;
                }

                void combine(HashStringAllocator * /*allocator*/, exec::arg_type<T> other) {
                    xor_ ^= other;
                }

                bool writeFinalResult(exec::out_type<OutputType> &out) {
                    out = xor_;
                    return true;
                }

                bool writeIntermediateResult(exec::out_type<IntermediateType> &out) {
                    out = xor_;
                    return true;
                }
            };
        };
    } // namespace

    void registerBitwiseXorAggregate(
        const std::string &prefix,
        bool withCompanionFunctions,
        bool onlyPrestoSignatures,
        bool overwrite) {
        const std::string name = prefix + kBitwiseXor;

        std::vector<std::shared_ptr<exec::AggregateFunctionSignature> > signatures;
        std::vector<std::string> typeList{"tinyint", "smallint", "integer", "bigint"};
        if (onlyPrestoSignatures) {
            typeList = {"bigint"};
        }
        for (const auto &inputType: typeList) {
            signatures.push_back(exec::AggregateFunctionSignatureBuilder()
                .returnType(inputType)
                .intermediateType(inputType)
                .argumentType(inputType)
                .build());
        }

        exec::registerAggregateFunction(
            name,
            std::move(signatures),
            [name](
        core::AggregationNode::Step step,
        const std::vector<TypePtr> &argTypes,
        const TypePtr &resultType,
        const core::QueryConfig & /*config*/)
        -> std::unique_ptr<exec::Aggregate> {
                POLLUX_USER_CHECK_EQ(argTypes.size(), 1, "{} takes one argument", name);
                auto inputType = argTypes[0];
                switch (inputType->kind()) {
                    case TypeKind::TINYINT:
                        return std::make_unique<
                            SimpleAggregateAdapter<BitwiseXorAggregate<int8_t> > >(
                            step, argTypes, resultType);
                    case TypeKind::SMALLINT:
                        return std::make_unique<
                            SimpleAggregateAdapter<BitwiseXorAggregate<int16_t> > >(
                            step, argTypes, resultType);
                    case TypeKind::INTEGER:
                        return std::make_unique<
                            SimpleAggregateAdapter<BitwiseXorAggregate<int32_t> > >(
                            step, argTypes, resultType);
                    case TypeKind::BIGINT:
                        return std::make_unique<
                            SimpleAggregateAdapter<BitwiseXorAggregate<int64_t> > >(
                            step, argTypes, resultType);
                    default:
                        POLLUX_USER_FAIL(
                            "Unknown input type for {} aggregation {}",
                            name,
                            inputType->toString());
                }
            },
            withCompanionFunctions,
            overwrite);
    }
} // namespace kumo::pollux::aggregate::prestosql
